package main 

import "fmt"
import "net"
import "protocol"
import "network"

var input_data string	

func read(conn *net.TCPConn) {
	buf := network.NewReceBuffer(int16(1024))
	for{
		n,e := conn.Read(buf.Space())
		if e != nil {
			fmt.Println("conn lost!")
			conn.Close()
			break
		}
		buf.Put(int16(n))

		for rec := buf.Take(); rec != nil; rec = buf.Take() {
			fmt.Println("rece:", rec)
		}
	}
}

func main() {
	// 输入名字
	fmt.Println("Inpute your name:")
	var name string
	fmt.Scan(&name)

	// 链接服务器
	Addr := &net.TCPAddr{net.IP{127,0,0,1},12345}
	conn, e := net.DialTCP("tcp4", nil, Addr)	
	if e != nil {
		fmt.Println("connect err")
	}

	// 接受信息
	go read(conn)

	// 发送登录信息
	var msg protocol.RequestLogin
	msg.User = name

	sender := network.NewSender(conn, 1024)
	sender.SendMessage(&msg)

	// 聊天信息
	for {
		fmt.Scan(&input_data)
		if input_data == "exit" {
			conn.Close()
			break
		} else {
			var c protocol.ChatContent
			c.Content = input_data
			sender.SendMessage(&c)
		}

	}
}
